package com.boot2.core.web;

import lombok.SneakyThrows;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author zhangweilin
 * @Description: RestTemplate拦截器处理 抽象实现
 * @date 2020/7/17
 */
@CommonsLog
public abstract class AbstractRestTemplateInterceptor implements RestTemplateInterceptor {

    protected ClientHttpResponse warpResponse(HttpRequest request,ClientHttpResponse clientHttpResponse) {
        traceResponse(request,clientHttpResponse);
        return clientHttpResponse;
    }

    @SneakyThrows
    protected void traceRequest(HttpRequest request, byte[] body) {
        if (log.isDebugEnabled()) {
            log.debug("=========================== resttemplate request begin ===========================");
            log.debug("uri  " + request.getURI());
            log.debug("method :  " + request.getMethod());
            log.debug("headers : " + request.getHeaders());
            log.debug("request body :  " + new String(body, "utf-8"));
            log.debug("=========================== resttemplate request end ============================");
        }
    }

    @SneakyThrows
    protected String traceResponse(HttpRequest request, ClientHttpResponse httpResponse) {
        StringBuilder inputStringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getBody(), "UTF-8"))) {
            String line = bufferedReader.readLine();
            while (line != null) {
                inputStringBuilder.append(line);
                inputStringBuilder.append('\n');
                line = bufferedReader.readLine();
            }
            if (log.isDebugEnabled()) {
                log.debug("============================ resttemplate response begin ============================");
                log.debug("Status code  " + httpResponse.getStatusCode());
                log.debug("Status text  :  " + httpResponse.getStatusText());
                log.debug("Headers      :  " + httpResponse.getHeaders());
                log.debug("Response body:  " + inputStringBuilder.toString());
                log.debug("============================= resttemplate response end =============================");
            }
        }
        return inputStringBuilder.toString();
    }

}
